import { login, getInfo, scanLogin, unifiedLoginSend } from '@/api/user'
import { getToken, setToken, removeToken, getCurrentOrg, setCurrentOrg, removeCurrentOrg } from '@/utils/auth'
import {resetRouter} from '@/router'
const state = {
  token: getToken(),
  name: null,
  currentOrgId: getCurrentOrg(), // 当前所在组织
  orgRoleList: [], // 当前用户的所有组织
  info: {},
  id: null,
}

const mutations = {
  SET_ID: (state, id) => {
    state.id = id
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_INFO: (state, info) => {
    state.info = info
  },
  SET_ROLES: (state, roles) => {
    state.orgRoleList = roles
  },
  SET_CURRENT_ORG: (state, role) => {
    state.currentOrgId = role
  },
}
// 获得用户信息后的统一处理办法
const infoResFun = (response, commit, resolve, reject) => {
  if(response.status === 200) {
    const { data: { user: { lastOrgId, orgRoleList }, token } } = response
    // token
    commit('SET_TOKEN', token)
    setToken(token)
    // 所有组织
    commit('SET_ROLES', orgRoleList)
    // 默认选中组织
    const orgid = lastOrgId ? lastOrgId : orgRoleList[0].orgId
    commit('SET_CURRENT_ORG', orgid)
    setCurrentOrg(orgid)
  } else {
    reject('信息验证失败，请确认正确后重新登录！')
  }
  resolve(response)
}
const actions = {
  // user login
  login({ commit }, userInfo) {
    console.log({ commit }, userInfo);
    const { username, password } = userInfo
    // 正式登录
    return new Promise((resolve, reject) => {
      login({ userName: username.trim(), password: password }).then(response => {
        infoResFun(response, commit, resolve, reject)
        // if(response.status === 200) {
        //   const { data: { user: { lastOrgId, orgRoleList }, token } } = response
        //   // token
        //   commit('SET_TOKEN', token)
        //   setToken(token)
        //   // 所有组织
        //   commit('SET_ROLES', orgRoleList)
        //   // 默认选中组织
        //   const orgid = lastOrgId ? lastOrgId : orgRoleList[0].orgId
        //   commit('SET_CURRENT_ORG', orgid)
        //   setCurrentOrg(orgid)
        // }
        // resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 公共数据平台获取信息
  unifiedLogin({ commit},codeInfo) {
    return new Promise((resolve, reject) => {
      unifiedLoginSend(codeInfo).then((res) => {
        infoResFun(res, commit, resolve, reject)
      }).catch(e => {
        console.log(e)
        reject(e)
      })
    })
  },
  // 钉钉扫码登录
  dingtalklogin ({ commit }, codeInfo) {
    return new Promise((resolve, reject) => {
      scanLogin(codeInfo).then(response => {
        infoResFun(response, commit, resolve, reject)
      }).catch(error => {
        resolve(error)
        reject(error)
      })
    })
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then((res) => {
        const { data } = res
        if (!data) {
          reject('Verification failed, please Login again.')
        }
        const { orgRoleList, lastOrgId, userName, id } = data
        // 默认选中组织
        const orgid = lastOrgId ? lastOrgId : orgRoleList[0].orgId
        commit('SET_CURRENT_ORG', orgid) // 当前组织
        setCurrentOrg(orgid)
        // 其他信息
        commit('SET_ID', id)
        commit('SET_NAME', userName) 
        commit('SET_ROLES', orgRoleList) // 所有组织
        commit('SET_INFO', data) // 当前用户所有信息
        resolve(data)
      }).catch(e => {
        console.log(e)
        reject(e)
      })
    })
  },
  
  changeOrg({ commit }, orgId) {
    return new Promise((resolve, reject) => {
      commit('SET_CURRENT_ORG', orgId)
      setCurrentOrg(orgId)
      resolve()
    })
  },
  // user logout
  logout({ commit, dispatch }) {
    return new Promise(resolve => {
      commit('SET_ID', null)
      commit('SET_NAME', null)
      commit('SET_TOKEN', null)
      commit('SET_CURRENT_ORG', null)
      commit('SET_ROLES', [])
      commit('SET_INFO', {})
      removeToken()
      removeCurrentOrg()
      resetRouter()
      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch('tagsView/delAllViews', null, { root: true })
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_ID', null)
      commit('SET_NAME', null)
      commit('SET_TOKEN', null)
      commit('SET_CURRENT_ORG', null)
      commit('SET_ROLES', [])
      commit('SET_INFO', {})
      removeToken()
      removeCurrentOrg()
      resetRouter()
      
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
